from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from models import Tag, Post
from extensions import db
from sqlalchemy import desc
import logging

logger = logging.getLogger('Personal_Blog_System')

# 创建标签API蓝图
tag_api = Blueprint('tag_api', __name__, url_prefix='/api/tags')

@tag_api.route('/', methods=['GET'])
def get_tags():
    """获取标签列表"""
    try:
        include_stats = request.args.get('include_stats', 'false').lower() == 'true'
        limit = request.args.get('limit', type=int)
        
        query = Tag.query
        
        if include_stats:
            # 按使用次数排序
            query = query.join(Post.tags).group_by(Tag.id).order_by(desc(func.count(Post.id)))
        else:
            query = query.order_by(Tag.name)
        
        if limit:
            query = query.limit(limit)
        
        tags = query.all()
        
        tags_data = []
        for tag in tags:
            tag_data = {
                'id': tag.id,
                'name': tag.name,
                'description': tag.description,
                'color': tag.color,
                'created_at': tag.created_at.isoformat(),
                'updated_at': tag.updated_at.isoformat()
            }
            
            if include_stats:
                # 统计文章数量
                post_count = Post.query.filter(Post.tags.contains(tag), Post.status == 'published').count()
                tag_data['post_count'] = post_count
            
            tags_data.append(tag_data)
        
        return jsonify({'success': True, 'data': tags_data})
        
    except Exception as e:
        logger.error(f"获取标签列表失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取标签列表失败'}), 500

@tag_api.route('/<int:tag_id>', methods=['GET'])
def get_tag(tag_id):
    """获取单个标签"""
    try:
        tag = Tag.query.get_or_404(tag_id)
        
        tag_data = {
        'id': tag.id,
        'name': tag.name,
        'description': tag.description,
            'color': tag.color,
            'created_at': tag.created_at.isoformat(),
            'updated_at': tag.updated_at.isoformat()
        }
        
        return jsonify({'success': True, 'data': tag_data})
        
    except Exception as e:
        logger.error(f"获取标签失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取标签失败'}), 500

@tag_api.route('/', methods=['POST'])
@login_required
def create_tag():
    """创建标签"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return jsonify({'success': False, 'message': '标签名称是必填字段'}), 400
        
        # 检查标签是否已存在
        existing_tag = Tag.query.filter_by(name=data['name']).first()
        if existing_tag:
            return jsonify({'success': False, 'message': '标签已存在'}), 400
        
        # 创建标签
        tag = Tag(
            name=data['name'],
            description=data.get('description', ''),
            color=data.get('color', '#6c757d')
        )
        
        db.session.add(tag)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '标签创建成功',
            'data': {'id': tag.id}
        }), 201
        
    except Exception as e:
        logger.error(f"创建标签失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '创建标签失败'}), 500

@tag_api.route('/<int:tag_id>', methods=['PUT'])
@login_required
def update_tag(tag_id):
    """更新标签"""
    try:
        tag = Tag.query.get_or_404(tag_id)
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            # 检查新名称是否已被其他标签使用
            existing_tag = Tag.query.filter(Tag.name == data['name'], Tag.id != tag_id).first()
            if existing_tag:
                return jsonify({'success': False, 'message': '标签名称已存在'}), 400
            
            tag.name = data['name']
        
        if 'description' in data:
            tag.description = data['description']
        
        if 'color' in data:
            tag.color = data['color']
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': '标签更新成功'})
        
    except Exception as e:
        logger.error(f"更新标签失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '更新标签失败'}), 500

@tag_api.route('/<int:tag_id>', methods=['DELETE'])
@login_required
def delete_tag(tag_id):
    """删除标签"""
    try:
        tag = Tag.query.get_or_404(tag_id)
        
        # 检查是否有文章使用此标签
        if Post.query.filter(Post.tags.contains(tag)).first():
            return jsonify({'success': False, 'message': '无法删除正在使用的标签'}), 400
        
        db.session.delete(tag)
        db.session.commit()
        
        return jsonify({'success': True, 'message': '标签删除成功'})
        
    except Exception as e:
        logger.error(f"删除标签失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除标签失败'}), 500

